import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyListener;
import java.util.ArrayList;

import javax.swing.JPanel;
import javax.swing.Timer;

public class Game extends JPanel {
	private ArrayList<Player>	players;
	private ArrayList<Weapon>	weapons;

	public Game() {
		players = new ArrayList<Player>();
		weapons = new ArrayList<Weapon>();
		
		setPlayers();
		setWeapons();
		setPlayersWeapon();

		Timer timer = new Timer( 100, new TimerHandler() );
		timer.start();

		addKeyListener( new ArrowControl( players.get( 0 ) ) );

		setFocusable( true );
	}
	
	public void setPlayers(){
		// Player( name, health, x, y );
		addPlayer( new Player( "Remy", 100, 10, 10 ) );
		
		// Player( name, health );
		addPlayer( new Player( "Niek", 100 ) );
	}
	public void setWeapons(){
		// Weapon( name, ammo, magazine, rateOfFire, damage ) {
		addWeapon( new Weapon( "Thompson", 180, 30, 100, 20 ) );
	}

	public void setPlayersWeapon(){
		players.get( 0 ).setWeapon( weapons.get( 0 ) );
		players.get( 1 ).setWeapon( weapons.get( 0 ) );
	}
	
	public void addPlayer( Player player ) {
		if( player != null )
			players.add( player );
	}

	public void addWeapon( Weapon weapon ) {
		if( weapon != null )
			weapons.add( weapon );
	}
	
	public void addPlayerWeapon( Player player, Weapon weapon ){
		Player p = getPlayer( player );
		Weapon w = getWeapon( weapon );
		if( w != null && p != null )
			p.setWeapon( w );
	}
	
	public Player getPlayer( Player player ){
		for( Player p : players ){
			if( p.equals( player ))
				return p;
		}
		return null;
	}

	public Weapon getWeapon( Weapon weapon ){
		for( Weapon w : weapons ){
			if( w.equals( weapons ))
				return w;
		}
		return null;
	}
	
	public void paintPlayer( Player p, Graphics2D g ) {
		int x = ( int ) p.getPosition().getX();
		int y = ( int ) p.getPosition().getY();

		Graphics2D g2d = ( Graphics2D ) g.create();

		// fillOval( x, y, w, h );
		g2d.fillOval( x, y, 10, 10 );

		g2d.setColor( Color.red );

		// rotate( radial, x, y );
		g2d.rotate( Math.toRadians( p.getDirection() ), x + 5, y + 5 );

		// fillRect( x, y, w, h );
		g2d.fillRect( x + 4, y + 5, 3, 10 );
	}

	public void paintComponent( Graphics g ) {
		super.paintComponent( g );
		setBackground( Color.WHITE );

		Graphics2D graphics = ( Graphics2D ) g;

		for( Player p : players ) {
			paintPlayer( p, graphics );
		}
	}

	class TimerHandler implements ActionListener {

		@Override
		public void actionPerformed( ActionEvent e ) {
			KeyListener[] keys = getKeyListeners();
			( ( ArrowControl ) keys[ 0 ] ).performActions();
			repaint();
		}

	}
}